package com.iwomy.secureplat.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iwomy.secureplat.common.core.exception.PlatformBizErrorCodes;
import com.iwomy.secureplat.common.core.util.MsgUtils;
import com.iwomy.secureplat.common.core.util.R;
import com.iwomy.secureplat.common.data.datascope.DataScope;
import com.iwomy.secureplat.common.excel.vo.ErrorMessage;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import com.iwomy.secureplat.platform.entity.BasicSensorEntity;
import com.iwomy.secureplat.platform.mapper.BasicSensorMapper;
import com.iwomy.secureplat.platform.service.BasicSensorService;
import com.iwomy.secureplat.platform.vo.BasicSensorExcelVO;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 传感器
 *
 * @author pig
 * @date 2023-12-22 19:16:00
 */
@Service
public class BasicSensorServiceImpl extends ServiceImpl<BasicSensorMapper, BasicSensorEntity> implements BasicSensorService {


	@Override
	public List<BasicSensorEntity> listByScope(BasicSensorEntity basicSensor) {
		LambdaQueryWrapper<BasicSensorEntity> wrapper = Wrappers.lambdaQuery(basicSensor);
		return this.baseMapper.selectListByScope(wrapper, new DataScope());
	}

	@Override
	public Page pageByScope(Page page, BasicSensorEntity basicSensor) {

		LambdaQueryWrapper<BasicSensorEntity> wrapper = Wrappers.lambdaQuery(basicSensor);
		return this.baseMapper.selectPageByScope(page, wrapper, new DataScope());
	}

	@Override
	public R importSensor(List<BasicSensorExcelVO> excelVOList, BindingResult bindingResult) {
		List<ErrorMessage> errorMessageList = (List<ErrorMessage>) bindingResult.getTarget();

		List<BasicSensorEntity> list = new ArrayList<>();
		List<String> sensorTypeCodeList = new ArrayList<>();
		List<String> collect = excelVOList.stream().map(BasicSensorExcelVO::getSensorTypeCode).distinct().collect(Collectors.toList());
		Map<String, List<Long>> duplicateRows = new HashMap<>();
		for (long i = 0; i < excelVOList.size(); i++) {
			BasicSensorExcelVO excelVO = excelVOList.get((int) i);
			String sensorTypeCode = excelVO.getSensorTypeCode();

			if (duplicateRows.containsKey(sensorTypeCode)) {
				duplicateRows.get(sensorTypeCode).add(i + 1);
			} else {
				List<Long> rowList = new ArrayList<>();
				rowList.add(i + 1);
				duplicateRows.put(sensorTypeCode, rowList);
			}
		}
		if (!duplicateRows.isEmpty()) {
			Set<String> errorMsg = new HashSet<>();
			errorMsg.add("表格中传感器ID重复，不允许新增");

			for (Map.Entry<String, List<Long>> entry : duplicateRows.entrySet()) {
				String sensorTypeCode = entry.getKey();
				List<Long> rowList = entry.getValue();
				if (rowList.size() > 1) {
					for (Long row : rowList) {
						errorMessageList.add(new ErrorMessage(row + 1, errorMsg));
					}
				}
			}
			if (CollUtil.isNotEmpty(errorMessageList) && errorMessageList.stream().anyMatch(e -> CollUtil.isNotEmpty(e.getErrors()))) {
				return R.failed(errorMessageList);
			}
		}
		if (!collect.isEmpty()) {
			list = this.list(Wrappers.<BasicSensorEntity>lambdaQuery().in(BasicSensorEntity::getSensorTypeCode, collect));
			sensorTypeCodeList = list.stream().map(BasicSensorEntity::getSensorTypeCode).collect(Collectors.toList());
		}

		List<String> finalSensorTypeCodeList = sensorTypeCodeList;


		excelVOList.stream().forEach(x -> {
			Set<String> errorMsg = new HashSet<>();
			if (!x.getSensorTypeCode().startsWith("0x")||x.getSensorTypeCode().length() != 6) {
				errorMsg.add("传感器ID格式错误，请参考0x0000");
			} else if (finalSensorTypeCodeList.stream().anyMatch(name -> name.equals(x.getSensorTypeCode()))) {
				errorMsg.add(MsgUtils.getMessage(PlatformBizErrorCodes.SENSOR_ID_EXIST));
			}
			errorMessageList.add(new ErrorMessage(x.getLineNum(), errorMsg));
			x.setState(20);

		});

		if (ObjectUtil.isNotEmpty(list)) {
			List<ErrorMessage> filteredList = errorMessageList.stream()
					.filter(errorMessage -> errorMessage.getErrors() != null && !errorMessage.getErrors().isEmpty())
					.collect(Collectors.toList());

			return R.failed(filteredList);
		}
		if (CollUtil.isNotEmpty(errorMessageList) && errorMessageList.stream().anyMatch(e -> CollUtil.isNotEmpty(e.getErrors()))) {
			return R.failed(errorMessageList);
		}
		return R.ok(this.saveBatch(BeanUtil.copyToList(excelVOList, BasicSensorEntity.class)));
	}
}